# Test MP3 file upload script

$audioFile = "test_audio.mp3"
$url = "http://localhost:8082/api/voiceprint/feature/add"
$groupId = "test_group_mp3"
$featureId = "test_mp3_" + (Get-Date -Format "yyyyMMdd_HHmmss")

Write-Host "Starting MP3 file upload test..."
Write-Host "File: $audioFile"
Write-Host "URL: $url"
Write-Host "GroupId: $groupId"
Write-Host "FeatureId: $featureId"

# Check if file exists
if (-not (Test-Path $audioFile)) {
    Write-Host "Error: File $audioFile does not exist" -ForegroundColor Red
    exit 1
}

$fileSize = (Get-Item $audioFile).Length
Write-Host "File size: $fileSize bytes"

try {
    # Read file content
    $fileBytes = [System.IO.File]::ReadAllBytes($audioFile)
    
    # Create multipart/form-data content
    $boundary = [System.Guid]::NewGuid().ToString()
    $LF = "`r`n"
    
    $bodyLines = @(
        "--$boundary",
        "Content-Disposition: form-data; name=`"groupId`"",
        "",
        $groupId,
        "--$boundary",
        "Content-Disposition: form-data; name=`"featureId`"",
        "",
        $featureId,
        "--$boundary",
        "Content-Disposition: form-data; name=`"audioFile`"; filename=`"$audioFile`"",
        "Content-Type: audio/mpeg",
        ""
    )
    
    $bodyText = $bodyLines -join $LF
    $bodyBytes = [System.Text.Encoding]::UTF8.GetBytes($bodyText + $LF)
    
    $endBoundaryBytes = [System.Text.Encoding]::UTF8.GetBytes($LF + "--$boundary--" + $LF)
    
    # Combine complete request body
    $totalBytes = New-Object byte[] ($bodyBytes.Length + $fileBytes.Length + $endBoundaryBytes.Length)
    [Array]::Copy($bodyBytes, 0, $totalBytes, 0, $bodyBytes.Length)
    [Array]::Copy($fileBytes, 0, $totalBytes, $bodyBytes.Length, $fileBytes.Length)
    [Array]::Copy($endBoundaryBytes, 0, $totalBytes, $bodyBytes.Length + $fileBytes.Length, $endBoundaryBytes.Length)
    
    Write-Host "Request body size: $($totalBytes.Length) bytes"
    
    # Send HTTP request
    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=$boundary")
    
    Write-Host "Uploading file..."
    $response = $webClient.UploadData($url, "POST", $totalBytes)
    $responseText = [System.Text.Encoding]::UTF8.GetString($response)
    
    Write-Host "Upload successful!" -ForegroundColor Green
    Write-Host "Server response: $responseText"
    
} catch {
    Write-Host "Upload failed: $($_.Exception.Message)" -ForegroundColor Red
    if ($_.Exception.InnerException) {
        Write-Host "Detailed error: $($_.Exception.InnerException.Message)" -ForegroundColor Red
    }
} finally {
    if ($webClient) {
        $webClient.Dispose()
    }
}

Write-Host "Test completed"